#!/bin/bash
#description: compilse install nginx server on centos7
SOFTDIR="/opt/tools"
USER="nginx"
GROUP="nginx"
VER="$1"
INSTALLDIR="/usr/local"
LOGDIR="/var/log/nginx"
CACHEDIR="/var/cache/nginx"

#判断参数个数是否符合
if [ $# -ne 1 ];then
        echo "Usage: $0 <nginx-version>"
        exit 2
fi

#编译安装nginx前，初始化
function init(){
	#判断目录是否存在
	[ ! -d $SOFTDIR ] && mkdir -p $SOFTDIR
        [ ! -d $INSTALLDIR ] && mkdir -p $INSTALLDIR
        [ ! -d $LOGDIR ] && mkdir -p $LOGDIR
        [ ! -d $CACHEDIR ] && mkdir -p $CACHEDIR
        #判断用户是否存在，若不存在就创建
        if ! id $USER &>/dev/null;then
                groupadd -g 3110 $GROUP
                useradd -u 3110 -g $GROUP -s /sbin/nologin $USER
        fi
        #授权缓存目录的属主和属组
        chown -R $USER:$GROUP $CACHEDIR
        #判断nginx和80端口是否暂用，如果暂用就禁用或停止
        if [ "`yum info nginx|grep Repo|awk -F: '{print $2}'`" == " installed" ];then
                systemctl stop nginx
                yum -y remove nginx
        fi
        if [ "` netstat -tunlp|grep 80|awk -p '{print $7}'|cut -d/ -f2`" == "httpd" ];then
                echo "this server install httpd server"
                systemctl stop httpd
        fi
        #安装依赖包
        yum -y install patch git pcre-devel openssl openssl-devel geoip-devel gcc gcc-c++ unzip zlib-devel gd-devel
	#编译安装pcre
        cd $SOFTDIR && [ ! -f pcre-8.41.tar.gz ] && wget https://jaist.dl.sourceforge.net/project/pcre/pcre/8.41/pcre-8.41.tar.gz
	tar xf pcre-8.41.tar.gz && cd pcre-8.41 && ./configure --prefix=/usr/local/pcre && make && make install
	#下载nginx_cache_purge模块
	cd $SOFTDIR && [ ! -f ngx_cache_purge-2.3.zip ] && wget http://soft.51yuki.cn/ngx_cache_purge-2.3.zip
	unzip ngx_cache_purge-2.3.zip &>/dev/null
	#
	cd $SOFTDIR && [ ! -f nginx_upstream_check_module-master.zip ] &&  wget http://soft.51yuki.cn/nginx_upstream_check_module-master.zip
	unzip nginx_upstream_check_module-master.zip
	/usr/bin/patch -p1 < ${SOFTDIR}/nginx_upstream_check_module-master/check_1.12.1+.patch
	#下载nginx-sticky-module模块实现基于cookie的绑定
	cd $SOFTDIR && [ ! -f nginx-sticky-module.zip ] && wget http://soft.51yuki.cn/nginx-sticky-module.zip
	unzip nginx-sticky-module.zip
	#################sticky模块说明信息##############
	#sticky [name=route] [domain=.foo.bar] [path=/] [expires=1h] [hash=index|md5|sha1] [no_fallback];
	#name: 可以为任何的string字符,默认是route
	#domain：哪些域名下可以使用这个cookie
	#path：哪些路径对启用sticky,例如path/test,那么只有test这个目录才会使用sticky做负载均衡
	#expires：cookie过期时间，默认浏览器关闭就过期，也就是会话方式。
	#no_fallbackup：如果设置了这个，cookie对应的服务器宕机了，那么将会返回502（bad gateway 或者 proxy error），建议不启用
	#nginx sticky模块不能与ip_hash同时使用

}
function install(){
        #判断nginx软件是否存在，不存在就下载
        cd $SOFTDIR && [ ! -f nginx-${VER}.tar.gz ] && wget http://nginx.org/download/nginx-${VER}.tar.gz
        #编译安装nginx
        [ ! -d nginx-${VER} ] && tar zxf nginx-${VER}.tar.gz
        cd nginx-${VER}
	./configure --prefix=${INSTALLDIR}/nginx-${VER} --pid-path=${INSTALLDIR}/nginx-${VER}/nginx.pid --lock-path=${INSTALLDIR}/nginx-${VER}/nginx.lock --error-log-path=${LOGDIR}/error_log --http-log-path=${LOGDIR}/access_log  --http-client-body-temp-path=${CACHEDIR}/client_temp --http-proxy-temp-path=${CACHEDIR}/proxy_temp --http-fastcgi-temp-path=${CACHEDIR}/fastcgi_temp --user=$USER --group=$GROUP --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_realip_module --with-http_secure_link_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-stream --with-stream_ssl_module --with-http_image_filter_module --with-pcre=${SOFTDIR}/pcre-8.41 --add-module=${SOFTDIR}/ngx_cache_purge-2.3 --add-module=${SOFTDIR}/nginx_upstream_check_module-master --add-module=${SOFTDIR}/nginx-sticky-module
        if [ $? -ne 0 ];then
                echo "compilse nginx fail"
                exit 2
       fi
       make && make install
       if [ $? -ne 0 ];then
                echo "install nginx fail"
                exit 2
       fi
       #创建软链接
       ln -s ${INSTALLDIR}/nginx-${VER} ${INSTALLDIR}/nginx
       #编写nginx的启动文件，启动nginx服务
       cat >/usr/lib/systemd/system/nginx.service <<EOF
        [Unit]
        Description=nginx - high performance web server
        Documentation=http://netkiller.github.io
        After=network-online.target remote-fs.target nss-lookup.target
        Wants=network-online.target
        [Service]
        Type=forking
        PIDFile=${INSTALLDIR}/nginx/nginx.pid
        ExecStartPre=${INSTALLDIR}/nginx/sbin/nginx -t -c ${INSTALLDIR}/nginx/conf/nginx.conf
        ExecStart=${INSTALLDIR}/nginx/sbin/nginx -c ${INSTALLDIR}/nginx/conf/nginx.conf
        ExecReload=/bin/kill -s HUP $MAINPID
        ExecStop=/bin/kill -s QUIT $MAINPID
        [Install]
        WantedBy=multi-user.target
EOF
      systemctl daemon-reload
      systemctl start nginx
      if [ "$(ss -tunlp|grep nginx|wc -l)" -gt 0 ];then
          echo "nginx start succfull"
      else
          echo "nginx start fail"
      fi
}

function main(){
        init
        install
}
main

